package com.net2s.ldap;

import java.util.Enumeration;

import org.apache.log4j.Logger;

import com.net2s.mail.Mail;
import com.net2s.utils.Messages;

import netscape.ldap.LDAPAttribute;
import netscape.ldap.LDAPAttributeSet;
import netscape.ldap.LDAPConnection;
import netscape.ldap.LDAPEntry;
import netscape.ldap.LDAPException;
import netscape.ldap.LDAPReferralException;
import netscape.ldap.LDAPSearchConstraints;
import netscape.ldap.LDAPSearchResults;
import netscape.ldap.LDAPUrl;



public class Ldap {
	
	static Logger log= Logger.getLogger(Ldap.class);
	
	/**
	 * 
	 * @param filter
	 * @param searchbase
	 * @return true si existe en LDAP y false si no existe
	 */
	
	public static boolean search( String filter,String searchbase )
	{
		log.info("Entra en search " + filter + " " + searchbase);
		
		Enumeration enumAttrs=null;
		LDAPConnection ld = null;
		LDAPEntry findEntry = null;
		int status = -1;
		boolean sinresultado=true;
		try {
			ld = new LDAPConnection();
			/* Connect to server */
			ld.connect( Messages.getString("LDAP.HOST"),new Integer(Messages.getString("LDAP.PORT")).intValue());//HOST Y PUERTO
			ld.authenticate( Messages.getString("LDAP.USER"), Messages.getString("LDAP.PASSWORD"));
			String MY_FILTER=filter;
			String MY_SEARCHBASE = searchbase;

			LDAPSearchConstraints cons = ld.getSearchConstraints();
			/* Setting the batchSize to one will cause the result
				   enumeration below to block on one result at a time,
				   allowing us to update a list or do other things as
				   results come in. */
			/* We could set it to 0 if we just wanted to get all
				   results and were willing to block until then */
			cons.setBatchSize( 1 );
			LDAPSearchResults res = ld.search( MY_SEARCHBASE,LDAPConnection.SCOPE_SUB,MY_FILTER,null,false,cons );

			/* Loop on results until finished */
			while ( res.hasMoreElements() ) {

				/* Next directory entry */
				try {
					findEntry = res.next();
				} catch ( LDAPReferralException e ) {
					log.info( "Search reference: " );
					LDAPUrl refUrls[] = e.getURLs();
					for (int i=0; i<refUrls.length; i++) {
						log.info( "\t" + refUrls[i].getUrl() );
					}
					continue;
				} catch ( LDAPException e ) {
					log.error( "Error: " + e.toString() );
					continue;
				}

				log.info( findEntry.getDN() );

				/* Get the attributes of the entry */
				LDAPAttributeSet findAttrs = findEntry.getAttributeSet();
				enumAttrs = findAttrs.getAttributes();
				log.info( "\tAttributes: " );


				/* Loop on attributes */
				while ( enumAttrs.hasMoreElements() ) {
					LDAPAttribute anAttr = (LDAPAttribute)enumAttrs.nextElement();
					String attrName = anAttr.getName();
					log.info( "\t\t" + attrName );
					/* Loop on values for this attribute */
					Enumeration enumVals = anAttr.getStringValues();
					if (enumVals != null) {
						while ( enumVals.hasMoreElements() ) {
							sinresultado=false;
							String aVal = ( String )enumVals.nextElement();
							log.info( "\t\t\t" + aVal );
						}
					}
				}
			}
			status = 0;
		} catch( LDAPException e ) {
			log.error( "Error: " + e.toString() );
			
		}

		/* Done, so disconnect */
		if ( (ld != null) && ld.isConnected() ) {
			try {
				ld.disconnect();
			} catch ( LDAPException e ) {
				log.error( "Error: " + e.toString() );
			}
		}
		if(sinresultado==true){
			log.info("La busqueda no produjo ningun resultado para " + filter);
			return false;
		}
		if(sinresultado==false){
			log.info("Search finalizada correctamente");
			
		}
		return true;

	}
}
